package com.li.network.lab_4;

import java.util.*;

public class Parser {

    public static HttpRequest parseRequest(List<String> message) {
        HttpRequest httpRequest = new HttpRequest();

        //解析请求行
        String[] field = message.getFirst().split(" ");
        httpRequest.setMethod(field[0]);
        httpRequest.setUrl(field[1]);
        httpRequest.setVersion(field[2]);

        //解析请求头
        Map<String, String> map = new LinkedHashMap<>();
        long headerCount = message.stream().skip(1).filter(line -> line.contains(":")).peek(line -> {
            String[] kv = line.split(": ");
            if (kv.length == 2 && kv[0] != null && kv[1] != null) {
                map.put(kv[0], kv[1]);
            }
        }).count();
        httpRequest.setHeaders(map);


        //解析请求体
        if (message.size() > headerCount + 1) {
            StringBuilder body = new StringBuilder();
            message.subList((int) (headerCount+2), message.size()).stream().peek(line -> {
                body.append(line + "\n");
            });
            httpRequest.setBody(body.toString());
        }
        return httpRequest;
    }

    public static HttpResponse parseResponse(List<String> message) {
        HttpResponse httpResponse = new HttpResponse();
        //解析状态行
        String[] field = message.getFirst().split(" ");
        httpResponse.setVersion(field[0]);
        httpResponse.setCode(field[1]);
        httpResponse.setDescription(field[2]);

        //解析响应头部
        Map<String, String> map = new LinkedHashMap<>();
        long headerCount = message.stream().filter(line -> line.contains(":")).peek(line -> {
            String[] kv = line.replace(" ", "").split(":");
            map.put(kv[0], kv[1]);
        }).count();
        httpResponse.setHeaders(map);

        //解析响应体
        if (message.size() > headerCount+1) {
            StringBuilder body = new StringBuilder();
            message.subList((int) (headerCount+2), message.size()).stream().peek(line -> {
                body.append(line).append("\n");
            });
            httpResponse.setBody(body.toString());
        }
        return httpResponse;
    }

}
